﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Thrift.Utility
{
    //标准请求，包括客户端服务器的IP及主机名，如果客户端是Web服务器，用户请求的URL和用户请求IP也会一并带到服务器端，用于做验证或请求限制。
    public class StandRequest<T>
    {
        private string SIGN_KEY = ConfigurationManager.AppSettings["ThriftSignKey"] ?? "Thrift_Sign";

        public string HostName { get; set; }

        public string IP { get; set; }

        public string RequestUrl { get; set; }

        public string UserRequestIP { get; set; }

        public DateTime RequestTime { get; set; }

        public string TimeStamp { get; set; }

        public string Sign { get; set; }

        public string MethodName { get; set; }

        public T Data { get; set; }

        public string SignTimestamp(string timeStamp)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] array = md5.ComputeHash(Encoding.UTF8.GetBytes(timeStamp + SIGN_KEY));
            return Convert.ToBase64String(array);
        }

        //验证客户请求是否合法
        public bool IsValid()
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] array = md5.ComputeHash(Encoding.UTF8.GetBytes(TimeStamp + SIGN_KEY));
            string sign = Convert.ToBase64String(array);
            return Sign.Equals(sign);
        }
    }
}
